<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workflows' }">工作流管理</el-breadcrumb-item>
          <el-breadcrumb-item>工作流详情</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="action-buttons">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
          <el-button type="primary" @click="handleEdit">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="success" @click="handleRun">
            <el-icon><VideoPlay /></el-icon>
            运行
          </el-button>
        </div>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <!-- 基本信息 -->
      <template #header>
        <div class="card-header">
          <span class="card-title">基本信息</span>
          <el-tag v-if="workflow.status" :type="getStatusType(workflow.status)">
            {{ workflow.status }}
          </el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ workflow.id }}</el-descriptions-item>
        <el-descriptions-item label="工作流名称">{{ workflow.name }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ workflow.description || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="定时调度">
          <el-tag v-if="workflow.cron_enabled" type="success">已启用</el-tag>
          <el-tag v-else type="info">未启用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Cron表达式">
          {{ workflow.cron_expression || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(workflow.created_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(workflow.updated_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人" :span="2">
          {{ workflow.created_by || '系统' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 工作流可视化 -->
    <el-card class="detail-card">
      <template #header>
        <span class="card-title">工作流可视化</span>
      </template>

      <div class="workflow-visualization">
        <WorkflowEditor
          v-model="workflowData"
          :readonly="true"
        />
      </div>
    </el-card>

    <!-- 工作流实例列表 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">执行实例列表</span>
          <el-button size="small" @click="refreshInstances">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table
        :data="instances"
        v-loading="instancesLoading"
        stripe
      >
        <el-table-column prop="id" label="实例ID" width="100" />
        <el-table-column prop="instance_name" label="实例名称" min-width="200" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getInstanceStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="trigger_type" label="触发方式" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.trigger_type === 'manual'" type="primary" size="small">手动</el-tag>
            <el-tag v-else type="info" size="small">定时</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时" width="100">
          <template #default="{ row }">
            {{ row.duration ? `${row.duration}s` : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewInstance(row)">查看详情</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDeleteInstance(row)"
              :disabled="['运行中', '暂停中', '已暂停', '等待中'].includes(row.status)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="instancePagination.page"
        v-model:page-size="instancePagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="instancesTotal"
        layout="total, sizes, prev, pager, next"
        class="pagination"
        @size-change="fetchInstances"
        @current-change="fetchInstances"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWorkflowDetail, getWorkflowInstances, runWorkflow, deleteWorkflowInstance } from '@/api/workflow'
import WorkflowEditor from '@/components/WorkflowEditor/index.vue'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()

const workflowId = ref(parseInt(route.params.id))
const loading = ref(false)
const workflow = ref({})

// 计算工作流数据格式，转换为Vue Flow格式
const workflowData = computed(() => {
  if (!workflow.value.workflow_definition || !workflow.value.workflow_definition.nodes) {
    return { nodes: [], edges: [] }
  }

  const definition = workflow.value.workflow_definition
  const edges = []
  const nodePositions = new Map()

  // 第一步：构建边的映射和入度统计
  const nodeMap = new Map()
  const inDegree = new Map()

  definition.nodes.forEach(node => {
    nodeMap.set(node.id, node)
    inDegree.set(node.id, 0)
  })

  // 统计入度并创建边
  definition.nodes.forEach(node => {
    if (node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        if (inDegree.has(nextId)) {
          inDegree.set(nextId, inDegree.get(nextId) + 1)
        }

        edges.push({
          id: `edge_${node.id}_${nextId}`,
          type: 'smoothstep',
          source: node.id,
          target: nextId,
          sourceHandle: 'source',
          targetHandle: 'target',
          animated: true,
          label: '',
          data: {}
        })
      })
    }
  })

  // 第二步：拓扑排序，按执行顺序排列节点
  const sortedNodes = []
  const queue = []

  // 找到所有入度为0的节点（起始节点）
  inDegree.forEach((degree, nodeId) => {
    if (degree === 0) {
      queue.push(nodeId)
    }
  })

  // BFS拓扑排序
  while (queue.length > 0) {
    const nodeId = queue.shift()
    sortedNodes.push(nodeId)

    const node = nodeMap.get(nodeId)
    if (node && node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        if (inDegree.has(nextId)) {
          inDegree.set(nextId, inDegree.get(nextId) - 1)
          if (inDegree.get(nextId) === 0) {
            queue.push(nextId)
          }
        }
      })
    }
  }

  // 如果有环或孤立节点，将剩余节点添加到末尾
  definition.nodes.forEach(node => {
    if (!sortedNodes.includes(node.id)) {
      sortedNodes.push(node.id)
    }
  })

  // 第三步：根据拓扑排序结果设置水平位置
  sortedNodes.forEach((nodeId, index) => {
    const x = 180 + index * 300
    const y = 90
    nodePositions.set(nodeId, { x, y })
  })

  // 转换节点格式
  const nodes = definition.nodes.map(node => {
    const position = nodePositions.get(node.id) || { x: 0, y: 0 }

    // 统一节点类型名称，确保与模板匹配
    let nodeType = node.type
    if (node.type === 'condition') {
      nodeType = 'condition_branch'
    } else if (node.type === 'data_processing') {
      nodeType = 'data_processing'
    } else if (node.type === 'create_experiment') {
      nodeType = 'create_experiment'
    } else if (node.type === 'download_data') {
      nodeType = 'download_data'
    }

    return {
      id: node.id,
      type: nodeType,
      position,
      data: {
        label: node.name || node.type,
        config: node.config || {}
      }
    }
  })

  return { nodes, edges }
})

const instances = ref([])
const instancesLoading = ref(false)
const instancesTotal = ref(0)
const instancePagination = reactive({
  page: 1,
  pageSize: 10
})


const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

const getStatusType = (status) => {
  const typeMap = {
    '运行中': 'primary',
    '已完成': 'success',
    '失败': 'danger',
    '暂停中': 'warning',
    '已暂停': 'info',
    '初始化': 'info'
  }
  return typeMap[status] || 'info'
}

const getInstanceStatusType = (status) => {
  const typeMap = {
    '运行中': 'primary',
    '已完成': 'success',
    '失败': 'danger',
    '暂停中': 'warning',
    '已暂停': 'info',
    '等待中': 'warning',
    '已取消': 'info',
    '初始化': 'info'
  }
  return typeMap[status] || 'info'
}

const fetchWorkflow = async () => {
  loading.value = true
  try {
    const data = await getWorkflowDetail(workflowId.value)
    workflow.value = data
  } catch (error) {
    console.error('获取工作流详情失败:', error)
    ElMessage.error('获取工作流详情失败')
  } finally {
    loading.value = false
  }
}

const fetchInstances = async () => {
  instancesLoading.value = true
  try {
    const data = await getWorkflowInstances({
      workflow_id: workflowId.value,
      page: instancePagination.page,
      page_size: instancePagination.pageSize
    })
    instances.value = data.items || []
    instancesTotal.value = data.total || 0
  } catch (error) {
    console.error('获取实例列表失败:', error)
    ElMessage.error('获取实例列表失败')
  } finally {
    instancesLoading.value = false
  }
}

const refreshInstances = () => {
  instancePagination.page = 1
  fetchInstances()
}

const handleBack = () => {
  router.push('/workflows')
}

const handleEdit = () => {
  router.push(`/workflows/${workflowId.value}/edit`)
}

const handleRun = async () => {
  try {
    await ElMessageBox.confirm('确定要运行这个工作流吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await runWorkflow(workflowId.value, {})
    ElMessage.success('工作流已启动')

    // 刷新实例列表
    setTimeout(() => {
      refreshInstances()
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('运行工作流失败:', error)
    }
  }
}

const handleViewInstance = (row) => {
  router.push(`/workflows/instances/${row.id}`)
}

const handleDeleteInstance = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除执行实例 "${row.instance_name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteWorkflowInstance(row.id)
    ElMessage.success('执行实例删除成功')

    // 刷新实例列表
    fetchInstances()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除执行实例失败:', error)
      ElMessage.error(error.response?.data?.detail || '删除执行实例失败')
    }
  }
}

onMounted(() => {
  fetchWorkflow()
  fetchInstances()
})
</script>

<style lang="scss" scoped>
.detail-card {
  margin-bottom: 20px;

  :deep(.el-card__header) {
    padding: 16px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.node-title {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .node-name {
    font-weight: 500;
    flex: 1;
  }
}

.node-detail {
  padding: 10px 0;
}

.config-json {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.6;
  max-height: 300px;
  overflow: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.page-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.workflow-visualization {
  height: 500px;

  :deep(.workflow-editor-container) {
    height: 100%;
  }
}
</style>
